<template>
  <je-form
    ref="formRef"
    class="je-func-simple"
    :rules="rules"
    :model="formState"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    :colon="false"
    size="small"
    autocomplete="off"
  >
    <je-collapse v-model:activeKey="activeKey" expand-icon-position="right">
      <je-collapse-panel key="1" header="基础信息">
        <je-form-item label="功能名称" name="FUNCINFO_FUNCNAME">
          <je-input v-model:value.trim="formState.FUNCINFO_FUNCNAME" disabled />
        </je-form-item>
        <je-form-item label="功能编码" name="FUNCINFO_FUNCCODE">
          <je-input v-model:value.trim="formState.FUNCINFO_FUNCCODE" disabled />
        </je-form-item>
        <je-form-item label="表编码" name="FUNCINFO_TABLENAME">
          <je-input v-model:value.trim="formState.FUNCINFO_TABLENAME" disabled />
        </je-form-item>
        <je-form-item label="表主键" name="FUNCINFO_PKNAME">
          <je-input v-model:value.trim="formState.FUNCINFO_PKNAME" disabled />
        </je-form-item>
        <je-form-item label="功能类型" name="FUNCINFO_FUNCTYPE">
          <je-select
            v-model:value="formState.FUNCINFO_FUNCTYPE"
            disabled
            allow-clear
            config-info="JE_FUNC_TYPE,formState.FUNCINFO_FUNCTYPE,code,S"
          />
        </je-form-item>
      </je-collapse-panel>

      <je-collapse-panel key="2" header="常用配置">
        <je-form-item label="子功能展示方式" name="FUNCINFO_CHILDSHOWTYPE">
          <je-select
            v-model:value="formState.FUNCINFO_CHILDSHOWTYPE"
            allow-clear
            config-info="JE_FUNC_CHILD_LAYOUT,formState.FUNCINFO_CHILDSHOWTYPE,code,S"
          />
        </je-form-item>
        <je-form-item label="数据录入方式" name="FUNCINFO_INSERTTYPE">
          <je-select
            v-model:value="formState.FUNCINFO_INSERTTYPE"
            allow-clear
            config-info="JE_FUNC_INSERTTYPE,formState.FUNCINFO_INSERTTYPE,code,S"
          />
        </je-form-item>
        <je-form-item label="每页展示条数" name="FUNCINFO_PAGESIZE">
          <je-input-number
            v-model:value="formState.FUNCINFO_PAGESIZE"
            :min="0"
            style="width: 100%"
          />
        </je-form-item>
        <je-form-item label="默认行高" name="FUNCINFO_COLUMN_WIDTH">
          <je-select
            v-model:value="formState.FUNCINFO_COLUMN_WIDTH"
            allow-clear
            config-info="JE_FUNC_ROWSIZE,formState.FUNCINFO_COLUMN_WIDTH,code,S"
          />
        </je-form-item>
        <je-form-item name="FUNCINFO_GRIDHIDELINES">
          <template #label>
            <je-checkbox v-model:checked="checkAll" @change="onCheckAllChange"> </je-checkbox>
            &nbsp;隐藏表格线
          </template>
          <je-checkbox-group
            v-model:value="formState.FUNCINFO_GRIDHIDELINES"
            style="margin-top: 5px"
          >
            <je-checkbox value="right">横线</je-checkbox>
            <je-checkbox value="bottom">竖线</je-checkbox>
          </je-checkbox-group>
        </je-form-item>
        <je-form-item label="启动简洁按钮条" name="FUNCINFO_SIMPLEBAR">
          <je-switch v-model:value="formState.FUNCINFO_SIMPLEBAR" mode="checkbox" />
          <span class="prompt">列表和表单的按钮条将变成精简模式。</span>
        </je-form-item>
        <je-form-item label="允许多选" name="FUNCINFO_MULTISELECT">
          <je-switch v-model:value="formState.FUNCINFO_MULTISELECT" mode="checkbox" />
          <span class="prompt">列表会出现多选框，用于批量选择。 </span>
        </je-form-item>
        <je-form-item label="表单列数" name="FUNCINFO_FORMCOLS">
          <je-select
            v-model:value="formState.FUNCINFO_FORMCOLS"
            config-info="JE_FUNC_LAYOUT_COLS,formState.FUNCINFO_FORMCOLS,code,S"
          />
        </je-form-item>
        <je-form-item label="表单宽度" name="FUNCINFO_FORMWIDTH">
          <je-input-number
            v-model:value="formState.FUNCINFO_FORMWIDTH"
            :min="0"
            addon-after="px"
            style="width: 100%"
          />
        </je-form-item>
        <je-form-item label="表单弹出宽高" name="FUNCINFO_WINFORMWH">
          <je-input
            v-model:value.trim="formState.FUNCINFO_WINFORMWH"
            placeholder="例：1024,768或100%,100%"
          />
        </je-form-item>
      </je-collapse-panel>
      <je-collapse-panel key="3" header="查询配置">
        <je-form-item name="FUNCINFO_WHERESQL">
          <template #label>
            <div class="iconWrap">
              <i
                class="fas fa-question-circle"
                :style="changeColor(unitTipShow)"
                @click="
                  clickTipView({
                    label: '过滤条件',
                    unitTpl: FILTER_UNITIPLE,
                  })
                "
                @mouseenter="unitTipShow = true"
                @mouseleave="unitTipShow = false"
              />
              过滤条件 <br />
            </div>
          </template>

          <je-textarea
            v-model:value="formState.FUNCINFO_WHERESQL"
            placeholder="and ..."
            :rows="4"
            @change="checkWhereSql('FUNCINFO_WHERESQL')"
          />
        </je-form-item>
        <je-form-item label="过滤条件描述" name="FUNCINFO_WHERESQL_DES">
          <je-textarea v-model:value="formState.FUNCINFO_WHERESQL_DES" :rows="4" />
        </je-form-item>
        <div class="tran" @click="changeSql('FUNCINFO_WHERESQL_DES', formState.FUNCINFO_WHERESQL)"
          >自然语言智能翻译</div
        >
        <je-form-item name="FUNCINFO_ORDERSQL">
          <template #label>
            <div class="iconWrap">
              <i
                class="fas fa-question-circle"
                style="color: #ebebeb; cursor: pointer"
                :style="changeColor(unitTipShow1)"
                @mouseenter="unitTipShow1 = true"
                @mouseleave="unitTipShow1 = false"
                @click="
                  clickTipView({
                    label: '排序条件',
                    unitTpl: OERDER_UNITPLE,
                  })
                "
              />
              排序条件 <br />
            </div>
          </template>
          <je-input
            v-model:value="formState.FUNCINFO_ORDERSQL"
            placeholder="order by..."
            @change="checkOrderSql('FUNCINFO_ORDERSQL')"
          />
        </je-form-item>
        <div class="sort">
          <span class="span" @click="changeSort('FUNCINFO_ORDERSQL', 'ORDER BY SY_ORDERINDEX ASC')"
            >排序字段正序</span
          >
          <span class="span" @click="changeSort('FUNCINFO_ORDERSQL', 'ORDER BY SY_CREATETIME DESC')"
            >创建时间倒序</span
          >
        </div>
        <je-form-item label="排序条件描述" name="FUNCINFO_ORDERSQL_DES">
          <je-input v-model:value="formState.FUNCINFO_ORDERSQL_DES" />
        </je-form-item>
        <div class="tran" @click="changeSql('FUNCINFO_ORDERSQL_DES', formState.FUNCINFO_ORDERSQL)"
          >自然语言智能翻译</div
        >
      </je-collapse-panel>
      <je-collapse-panel key="4" header="功能描述">
        <je-form-item label="功能描述" name="FUNCINFO_FUNCREMARK">
          <je-textarea v-model:value="formState.FUNCINFO_FUNCREMARK" :rows="4" />
        </je-form-item>
      </je-collapse-panel>
    </je-collapse>
  </je-form>
</template>

<script>
  import { ref, toRefs, defineComponent, reactive, onMounted, watch } from 'vue';

  import { Collapse, Form, Modal, Checkbox, Input, Select, InputNumber, Switch } from '@jecloud/ui';

  import { FILTER_UNITIPLE, OERDER_UNITPLE } from '@/helper/tip-constant.jsx';

  import VueEvent from '@/helper/event';

  import {
    GetListBaseConfig as EasyConfigGet,
    baseConfigSave as EasyConfigSave,
    ChangeTranslateSql,
  } from '@/api/index';

  const getFormState = () => {
    return {
      FUNCINFO_FUNCNAME: '',
      FUNCINFO_FUNCCODE: '',
      FUNCINFO_TABLENAME: '',
      FUNCINFO_PKNAME: '',
      FUNCINFO_FUNCTYPE: '',
      FUNCINFO_CHILDSHOWTYPE: '',
      FUNCINFO_INSERTTYPE: '',
      FUNCINFO_PAGESIZE: '',
      FUNCINFO_COLUMN_WIDTH: '',
      FUNCINFO_GRIDHIDELINES: '',
      FUNCINFO_SIMPLEBAR: '',
      FUNCINFO_MULTISELECT: '',
      FUNCINFO_FORMCOLS: '',
      FUNCINFO_FORMWIDTH: '',
      FUNCINFO_WINFORMWH: '',
      FUNCINFO_WHERESQL: '',
      FUNCINFO_WHERESQL_DES: '',
      FUNCINFO_ORDERSQL: '',
      FUNCINFO_ORDERSQL_DES: '',
      FUNCINFO_FUNCREMARK: '',
    };
  };
  const GRIDHIDELINES = ['right', 'bottom'];
  export default defineComponent({
    name: 'FunctionSimple',
    components: {
      JeCollapse: Collapse,
      JeCollapsePanel: Collapse.Panel,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeSelect: Select,
      JeInput: Input,
      JeTextarea: Input.TextArea,
      JeInputNumber: InputNumber,
      JeCheckbox: Checkbox,
      JeCheckboxGroup: Checkbox.Group,
      JeSwitch: Switch,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['btnClick'],
    setup(props, { expose }) {
      const state = reactive({
        visible: true,
        activeKey: ['1', '2', '3', '4'],
        formRef: ref(),
        funcId: props.recordData.JE_CORE_FUNCINFO_ID,
        formState: reactive(getFormState()),
        labelCol: {
          style: { width: '120px' },
        },
        wrapperCol: {},
        rules: {
          FUNCINFO_PAGESIZE: [{ required: true, message: '该输入项为必填项', trigger: 'change' }],
          FUNCINFO_FORMCOLS: [{ required: true, message: '该输入项为必填项', trigger: 'change' }],
        },
        checkAll: false,
        unitTipShow: false,
        FILTER_UNITIPLE,
        OERDER_UNITPLE,
        unitTipShow1: false,
      });
      watch(
        () => state.formState.FUNCINFO_GRIDHIDELINES,
        (value) => {
          if (value) {
            const newValue = value.split(',');
            if (newValue.length == GRIDHIDELINES.length) {
              state.checkAll = true;
            } else {
              state.checkAll = false;
            }
          }
        },
        { deep: true, immediate: true },
      );
      const methods = {
        clickTipView(item) {
          Modal.alert({
            content: item.unitTpl,
            title: item.label,
            icon: 'fal fa-info-circle',
            status: 'info',
            width: '460',
          });
        },
        handleOk() {
          const value = state.formState['FUNCINFO_ORDERSQL'];
          if (value) {
            const str = 'order by ';
            if (value.replace(/(^\s*)|(\s*$)/g, '').length <= str.length) {
              Modal.alert('请输入正确的排序条件', 'info');
              return false;
            }
          }
          return state.formRef
            .validate()
            .then(methods.handleSubmit)
            .catch((error) => {
              console.error(error);
            });
        },

        handleSubmit() {
          const params = {};
          params.tableCode = 'JE_CORE_FUNCINFO';
          params.JE_CORE_FUNCINFO_ID = state.funcId;
          params._updatefields_ = [];

          Object.keys(state.formState).forEach((item) => {
            params[item] = state.formState[item];
            params._updatefields_.push(item);
          });

          params._updatefields_ = params._updatefields_.join(',');
          return EasyConfigSave(params)
            .then((res) => {
              VueEvent.emit('refleshTreeData');

              Modal.message(res.message, 'success');
            })
            .catch((err) => {
              console.log('error', err);
              Modal.alert(err.message, 'error');
            });
        },

        getData() {
          const params = {
            pkValue: state.funcId,
          };
          EasyConfigGet(params)
            .then((res) => {
              Object.keys(state.formState).forEach((item) => {
                state.formState[item] = res[item];
              });
            })
            .catch((err) => {
              console.log('error', err);
              Modal.alert(err.message, 'error');
            });
        },

        onCheckAllChange() {
          state.formState.FUNCINFO_GRIDHIDELINES = state.checkAll ? 'right,bottom' : '';
        },

        changeSql(key, sql) {
          if (!sql) {
            Modal.alert('条件不能为空', 'warning');
            return false;
          }

          const params = {
            funcId: state.funcId,
            sql,
          };
          ChangeTranslateSql(params)
            .then((res) => {
              state.formState[key] = res;

              // Modal.notice('操作成功', 'success');
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        changeSort(key, value) {
          state.formState[key] = value;
        },

        checkOrderSql(key) {
          const value = state.formState[key];
          if (value) {
            const reg1 = /^order by /gi;
            if (!reg1.test(value)) {
              state.formState[key] = 'order by ';
            }
          }
        },
        // 改变tip浮上去的颜色
        changeColor(flag) {
          if (flag) {
            return 'cursor:pointer;color: #3265F5';
          }
          return 'cursor:pointer;color: #ebebeb';
        },
        checkWhereSql(key) {
          const value = state.formState[key];
          if (value) {
            const reg1 = /^and /gi;
            if (!reg1.test(value)) {
              state.formState[key] = 'and ';
            }
          }
        },
      };
      // 暴露doSave方法，用于drawer保存关闭使用，返回Promise，成功关闭
      expose({ doSave: methods.handleOk });
      onMounted(() => {
        methods.getData();
      });
      return { ...toRefs(state), ...methods };
    },
  });
</script>
<style lang="less">
  .je-func-simple .ant-collapse-item > .ant-collapse-header {
    padding: 0 16px;
    height: 32px;
    line-height: 32px;
  }
</style>
<style lang="less" scoped>
  .je-func-simple {
    height: 100%;
    width: 100%;
    .title {
      font-size: 16px;
    }
    .prompt {
      margin: 0 0 0 10px;
      font-size: 14px;
      color: #3265f5;
      vertical-align: top;
      font-style: italic;
    }
    .sort {
      margin: 0 0 10px 0;
      color: #3265f5;
      text-align: right;
      cursor: pointer;
      .span {
        margin: 0 0 0 10px;
      }
    }
    .tran {
      margin: 0 0 10px 0;
      color: #539500;
      text-align: right;
      cursor: pointer;
    }
  }
</style>
